<script setup lang="ts">
import { ref } from "vue";
import { useUserAPI } from "@/services/user";
import { useUploadAPI } from "@/services/upload";
import { ElMessage } from "element-plus";
import { useUserStore } from "@/stores/user";
import { UploadFilled, Picture } from "@element-plus/icons-vue";

const userStore = useUserStore();

const visible = defineModel("show");
const emit = defineEmits(["uploaded"]);
const userAPI = useUserAPI();
const uploadAPI = useUploadAPI();

const uploadForm = ref({
  songFile: null as File | null,
  coverFile: null as File | null,
  songName: "",
  lyric: "", // 歌词
});

const coverPreview = ref("");
const uploading = ref(false);
const musicFileInput = ref<HTMLInputElement | null>(null);
const coverFileInput = ref<HTMLInputElement | null>(null);

const handleCoverChange = (e: Event) => {
  const file = (e.target as HTMLInputElement).files?.[0];
  if (file) {
    uploadForm.value.coverFile = file;
    coverPreview.value = URL.createObjectURL(file);
  }
};

const handleMusicFileChange = (e: Event) => {
  const file = (e.target as HTMLInputElement).files?.[0];
  if (file) {
    uploadForm.value.songFile = file;
  }
};

const resetForm = () => {
  uploadForm.value = {
    songFile: null,
    coverFile: null,
    songName: "",
    lyric: "",
  };
  coverPreview.value = "";
};

const handleUpload = async () => {
  if (
    !uploadForm.value.songFile ||
    !uploadForm.value.coverFile ||
    !uploadForm.value.songName
  ) {
    ElMessage.warning("请填写完整信息");
    return;
  }

  try {
    uploading.value = true;

    // 先上传音乐文件和封面
    const [musicRes, coverRes] = await Promise.all([
      uploadAPI.uploadFile(uploadForm.value.songFile),
      uploadAPI.uploadFile(uploadForm.value.coverFile),
    ]);

    // 准备音乐信息
    const musicData = {
      musicName: uploadForm.value.songName,
      musicAuthor: userStore.username,
      musicUrl: musicRes.msg, // 音乐文件的OSS地址
      musicCoverUrl: coverRes.msg, // 封面图片的OSS地址
      lyric: uploadForm.value.lyric || "",
    };

    // 提交音乐信息
    await userAPI.postUploadSong(musicData);

    ElMessage.success("上传成功");
    emit("uploaded");
    visible.value = false;
    resetForm();
  } catch (error) {
    console.error(error);
    ElMessage.error("上传失败，请重试");
  } finally {
    uploading.value = false;
  }
};
</script>

<template>
  <el-dialog
    v-model="visible"
    width="500px"
    class="upload-song-dialog"
    align-center
    destroy-on-close
    @closed="resetForm"
  >
    <template #header>
      <div class="text-xl font-medium">上传音乐</div>
    </template>

    <el-form :model="uploadForm" label-position="top" class="px-6">
      <el-form-item class="mb-6">
        <div
          class="upload-area border-2 border-dashed border-gray-300 rounded-lg p-6 text-center hover:border-[#d51007] transition-colors cursor-pointer"
        >
          <input
            type="file"
            accept="audio/*"
            class="hidden"
            ref="musicFileInput"
            @change="handleMusicFileChange"
          />
          <div
            @click="musicFileInput?.click()"
            class="flex flex-col items-center"
          >
            <el-icon class="text-3xl text-gray-400 mb-2">
              <upload-filled />
            </el-icon>
            <div class="text-gray-600 mb-1">点击或拖拽音乐文件到此处</div>
            <div class="text-gray-400 text-sm">支持 MP3、WAV 格式</div>
          </div>
          <div v-if="uploadForm.songFile" class="mt-4 text-sm text-[#d51007]">
            已选择: {{ uploadForm.songFile.name }}
          </div>
        </div>
      </el-form-item>

      <el-form-item class="mb-6">
        <div class="flex items-start gap-4">
          <div class="flex-1">
            <div
              class="upload-area border-2 border-dashed border-gray-300 rounded-lg p-4 text-center hover:border-[#d51007] transition-colors cursor-pointer"
            >
              <input
                type="file"
                accept="image/*"
                class="hidden"
                ref="coverFileInput"
                @change="handleCoverChange"
              />
              <div
                @click="coverFileInput?.click()"
                class="flex flex-col items-center"
              >
                <el-icon class="text-2xl text-gray-400 mb-1">
                  <picture />
                </el-icon>
                <div class="text-gray-600 text-sm">上传封面图片</div>
              </div>
            </div>
          </div>
          <img
            v-if="coverPreview"
            :src="coverPreview"
            class="w-24 h-24 object-cover rounded-lg shadow"
          />
        </div>
      </el-form-item>

      <el-form-item class="mb-6">
        <el-input
          v-model="uploadForm.songName"
          size="large"
          placeholder="歌曲名称"
          prefix-icon="el-icon-music-note"
        />
      </el-form-item>

      <el-form-item>
        <el-input
          v-model="uploadForm.lyric"
          type="textarea"
          :rows="6"
          placeholder="歌词 (选填)"
          resize="none"
          class="song-lyric"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="flex justify-end gap-3 px-6">
        <el-button
          plain
          size="large"
          @click="visible = false"
          class="!border-gray-300 !text-gray-600 hover:!border-gray-400 hover:!text-gray-700"
        >
          取消
        </el-button>
        <el-button
          type="primary"
          size="large"
          :loading="uploading"
          @click="handleUpload"
          class="!bg-[#d51007] !border-[#d51007] hover:!bg-[#b31007] hover:!border-[#b31007]"
        >
          {{ uploading ? "上传中..." : "确认上传" }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped>
.upload-area {
  min-height: 120px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.song-lyric :deep(.el-textarea__inner) {
  font-family: inherit;
  line-height: 1.6;
}

:deep(.el-dialog__header) {
  padding-bottom: 16px;
  margin-bottom: 0;
  border-bottom: 1px solid #e5e7eb;
}

:deep(.el-dialog__footer) {
  padding-top: 16px;
  margin-top: 16px;
  border-top: 1px solid #e5e7eb;
}
</style>
